﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Mail;
using System.Configuration;
using System.Web;

namespace GoodStuff.Diagnostics
{
    internal class ExceptionHandlerMailer : IExceptionHandler
    {
        private ExceptionHandlerMailerConfiguration _config;

        public ExceptionHandlerMailer(ExceptionHandlerMailerConfiguration config)
        {
            _config = config;

            //validate the configuration.
            if (string.IsNullOrEmpty(_config.From))
            {
                throw new ConfigurationErrorsException(string.Format("ExceptionMailer-Module; a required From value not configured. "));
            }

            if (string.IsNullOrEmpty(_config.Recipients))
            {
                throw new ConfigurationErrorsException(string.Format("ExceptionMailer-Module; a required Recipients value not configured. "));
            }
        }

        public void HandleException(Exception error, System.Web.HttpRequest request)
        {
            Exception baseError = error.GetBaseException();

            //send Email to support
            MailMessage msg = new MailMessage();

            string subject = baseError.Message; //subject pakt de baseException
            if (subject != null && subject.IndexOf("\r\n") > 0)
            {
                //subject contains newlines, take the first one.
                subject = subject.Split(new char[] { '\r', '\n' })[0];
            }
            if (subject != null && subject.Length > 128)
            {
                subject = subject.Substring(0, 128) + "...";
            }

            msg.Subject = "[" + request.Url.Host + "] : " + subject;
            msg.From = new MailAddress(_config.From);
            msg.IsBodyHtml = false;

            string[] toSplitted = _config.Recipients.Split(new char[] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string to in toSplitted)
            {
                msg.To.Add(to);
            }

            //Show extended userinformation
            string userDetails = null;
            if (request.IsAuthenticated && HttpContext.Current != null && HttpContext.Current.User != null)
            {
                userDetails = HttpContext.Current.User.Identity.Name + " @ ";
            }
            userDetails = string.Concat(userDetails, request.UserHostAddress, ", UserAgent=", request.UserAgent);

            msg.Body = String.Format(
                "Exception: {0}\n\n"
                + "Inner exception: {1}\n\n"
                + "Url: {2}\n\n"
                + "User: {3}\n\n"
                + "Details:\n{4}",

                error.Message,
                error.InnerException != null ? error.InnerException.Message : "null",
                request.Url.ToString(),
                userDetails,
                error.ToString("\n")            // <--- extension 
                );

            SmtpClient smtp = new SmtpClient();
            smtp.Send(msg);
        }       

        public IList<ExceptionHandlerExclude> Excludes
        {
            get { return _config.Excludes; }
        }
    }
}
